<?php

namespace App\Models;

use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'title', 'description', 'image', 'on_sale',
        'rating', 'sold_count', 'review_count', 'price',
        'category_id'
    ];
    protected $casts = [
        'on_sale' => 'boolean', // on_sale 是一个布尔类型的字段
    ];

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            $model->seller_id = Admin::user()->id;
        });
    }

    public function getImagesAttribute()
    {
        $images = [];

        foreach ($this->skus as $item) {
            $images[] = getStaticUrl($item->image);
        }

        return $images;
    }

    // 与商品SKU关联
    public function skus()
    {
        return $this->hasMany(ProductSku::class);
    }

    public function getImageUrlAttribute()
    {
        return getStaticUrl($this->attributes['image']);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
